// ==UserScript==
// @name         药链通增强版
// @namespace    http://tampermonkey.net/
// @version      2025-09-01
// @description  药链通网站增强工具，支持订单号、选中文本、剪辑版文本、生成二维码/条码，工具栏隐藏、收缩，
// @author       Wei
// @match        *://ylt.cdhywl.cn/*
// @match        https://ylt.cdhywl.cn/pt/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=ylt.cdhywl.cn
// @run-at       document-end
// @grant        GM_setClipboard
// @grant        GM_addStyle
// @grant        GM_download
// @grant        GM_xmlhttpRequest
// @connect      gitee.com
// @require      https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js
// @require      https://cdn.bootcdn.net/ajax/libs/jsbarcode/3.11.5/JsBarcode.all.min.js
// @updateURL    https://gitee.com/canqing86/tampermon/raw/master/ylt.user.js
// @downloadURL  https://gitee.com/canqing86/tampermon/raw/master/ylt.user.js
// ==/UserScript==

(function() {
    'use strict';

    /*备用引用
    // @require      https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js
    // @require      https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js
    */

    let autoHideTimer = null;// 全局变量 - 自动隐藏工具栏

    // ============= 工具栏可配置参数 =============
    const TOOLBAR_CONFIG = {
        top: '1px',                     // 工具栏距离顶部的距离
        left: '50%',                    // 工具栏水平居中
        bgColor: 'rgba(245, 247, 250, 0.8)', // 工具栏背景颜色（带透明度）
        zIndex: 9998,                   // 工具栏层级
        padding: '8px 15px',            // 工具栏内边距
        gap: '40px'                     // 按钮间距（增大间距）
    };

    // ============= 条码可配置参数 =============
    const BARCODE_CONFIG = {
        format: "CODE128",              // 条码格式
        lineColor: "#000000",           // 条码颜色
        width: 2,                       // 条码线条宽度
        height: 80,                     // 条码高度（增大高度）
        displayValue: true,             // 是否显示文本
        fontSize: 16,                   // 文本字号
        margin: 30                      // 条码边距（增大边距）
    };

    const API_CONFIG = {
        //城配
        rematchDistribution: {
            url: 'https://ylt.cdhywl.cn/center.web/order/rematchDistribution',
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            bodyTemplate: 'orderCode=${orderCode}'
        },
        //改中通 cid=def60da5927244a8839d0a4ed170c2eb 代表中通
        detailChangeOrderLineMatchZT: {
            url: 'https://ylt.cdhywl.cn/center.web/order/detailChangeOrderLineMatch',
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            bodyTemplate: 'cid=def60da5927244a8839d0a4ed170c2eb&ordercode=${orderCode}'
        },
        //改安能
        detailChangeOrderLineMatchAN: {
            url: 'https://ylt.cdhywl.cn/center.web/order/detailChangeOrderLineMatch',
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            bodyTemplate: 'cid=058f1578dc3f4ca0a2b5e4f8385069c8&ordercode=${orderCode}'
        },
        //过审
        verify: {
            url: 'https://ylt.cdhywl.cn/center.web/order/verify',
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            bodyTemplate: 'uid=845138ac42174208870428210a4967e8&ordercode=${orderCode}&verifyStatus=1&verifyDescription=&costMainLine=&test=false'
        },
        //订单详情
        orderInfo: {
            url: 'https://ylt.cdhywl.cn/center.web/order/info',
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            bodyTemplate: 'sourceid=chengduhuayao&ordercode=${orderCode}'
        },
        //重新匹配
        rematchLine: {
            url: 'https://ylt.cdhywl.cn/center.web/order/rematchLine',
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            bodyTemplate: 'orderCode=${orderCode}'
        },
        //搜索通讯录收货人
        SearchInfo: {
            url: 'https://ylt.cdhywl.cn/center.web/contacts/searchList',
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
            bodyTemplate: '_size=25&_offset=0&sourceid=chengduhuayao&companyName=${companyName}&name=${name}&mobile=${mobile}&phone=${phone}&address=${address}'
        },



    };

    // ====================================

    GM_addStyle(`
    /* 工具栏容器 */
    #ylt-helper-container {
        position: fixed;
        top: ${TOOLBAR_CONFIG.top};
        left: ${TOOLBAR_CONFIG.left};
        transform: translateX(-50%);
        background: ${TOOLBAR_CONFIG.bgColor};
        padding: ${TOOLBAR_CONFIG.padding};
        z-index: ${TOOLBAR_CONFIG.zIndex};
        display: flex;
        gap: ${TOOLBAR_CONFIG.gap};
        flex-wrap: wrap;
        border-radius: 4px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        display: none; /* 初始隐藏 */
        height: ${isMobileDevice() ? '55px' : 'auto'}; /* 高度设置 手机/PC */
    }
    #ylt-helper-container.active {
        display: flex; /* 激活后显示 */
    }
     /* 主菜单按钮样式 */
    #ylt-helper-container button {
        padding: 5px 10px;
        background: #409eff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        white-space: nowrap;
    }
    #ylt-helper-container button:hover {
        background: #66b1ff;
    }
    .ylt-helper-dropdown {
        position: relative;
        display: inline-block;
    }

    /* 下拉菜单样式 */
    .ylt-helper-dropdown-content {
        display: none;
        position: absolute;
        background-color: #f9f9f9;
        min-width: 120px;
        box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
        z-index: 1;
        border-radius: 4px;
        padding: 8px 0;
    }
    .ylt-helper-dropdown-content button {
        color: black;
        padding: 8px 16px;
        text-decoration: none;
        display: block;
        width: 100%;
        text-align: left;
        background: none;
        border: none;
        border-radius: 0;
        margin: 4px 0;
        line-height: 1.6;
    }
    .ylt-helper-dropdown-content button:hover {
        background-color: #f1f1f1;
        color: #409eff;
    }

    /* 条形码/二维码显示区域 */
    #barcode-display {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 0 20px rgba(0,0,0,0.3);
        z-index: 9999;
        text-align: center;
        min-width: 300px;
        max-width: 90%;
        max-height: 90vh;
        overflow: auto;
    }
    #barcode-container, #qrcode-container {
        margin: 15px auto;
        width: 100%;
    }
    #barcode-container svg {
        width: 100%;
        max-width: 400px;
        height: auto;
        display: block;
        margin: 0 auto;
    }
    #qrcode-container canvas {
        max-width: 100%;
        height: auto;
        display: block;
        margin: 0 auto;
    }

    /* 自定义弹窗容器 */
    #ylt-custom-alert {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        max-width: 800px;
        max-height: 80vh;
        background: white;
        border-radius: 8px;
        box-shadow: 0 0 20px rgba(0,0,0,0.3);
        z-index: 99999;
        display: flex;
        flex-direction: column;
        overflow: hidden;
    }
    /* 固定标题栏 */
    .ylt-alert-header {
        padding: 12px 20px;
        background: #409eff;
        color: white;
        font-weight: bold;
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: relative;
        z-index: 2;
    }
    /* 自定义弹窗 可滚动内容区 */
    .ylt-alert-content {
        white-space: pre-wrap;
        font-family: monospace;
        line-height: 1.6;
        padding: 20px;
        padding-left: 15px;
        overflow-y: auto;
        max-height: calc(80vh - 56px);
    }

    /* 符号颜色强化 */
    .ylt-alert-content span[style*="color"] {
        margin-right: 8px;
    }

    /* 关闭按钮 */
    .ylt-alert-close {
        background: none;
        border: none;
        color: white;
        font-size: 24px;
        cursor: pointer;
        padding: 0 10px;
    }


    /* 移动端优化 */
    @media (hover: none) {
        #ylt-helper-container button {
            padding: 10px 15px !important;
            font-size: 16px !important;
            margin: 5px 0 !important;
        }
        .ylt-helper-dropdown-content {
            min-width: 180px !important;
        }
        .ylt-helper-dropdown-content button {
            padding: 12px 20px !important;
            font-size: 16px !important;
        }
    }
`);



    // 在脚本开头添加设备检测函数
    function isMobileDevice() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }


    // 在脚本初始化部分添加打印页面检测
    if (window.location.href.includes('/print/tag')) {
        // 如果是打印页面，则不创建工具栏
        return;
    }
    // 全局缓存行政区划数据
    let areaDataCache = null;
    let areaDataLoadAttempted = false; // 防止重复尝试加载失败

    // 初始化变量
    let currentBarcodeIndex = 0;
    let barcodeDisplay = null;
    let barcodeData = [];
    //let displayMode = 'both'; // 默认显示两者
    let displayMode = 'barcode'; // 默认显示条码

    // 创建激活按钮（位置可在此处调整）
    function createActivationButton() {
        const isMobile = isMobileDevice();
        const btn = document.createElement('div');
        btn.id = 'ylt-activation-btn';
        btn.title = '点击显示/隐藏工具栏';

        // 激活按钮样式
        btn.style.position = 'fixed';
        btn.style.top = '10px';
        btn.style.right = isMobile ? '30px' : '18%';
        btn.style.width = isMobile ? '80px' : '30px'; //移动端80px  PC端30px
        btn.style.height = isMobile ? '80px' : '30px';
        btn.style.backgroundColor = '#f0f0f0';
        btn.style.border = '1px solid #ddd';
        btn.style.borderRadius = '50%';
        btn.style.cursor = 'pointer';
        btn.style.zIndex = '9997';
        btn.style.opacity = isMobile ? '0.8' : '0.2';
        btn.style.transition = 'opacity 0.3s';
        btn.style.display = 'flex';
        btn.style.justifyContent = 'center';
        btn.style.alignItems = 'center';
        btn.style.fontWeight = 'bold';
        btn.style.fontSize = isMobile ? '18px' : '14px';
        btn.textContent = '⚙️';

        // 点击事件 显示或者隐藏工具栏，自动隐藏工具栏
        btn.onclick = () => {
            const container = document.getElementById('ylt-helper-container');

            // 清除现有定时器
            if (autoHideTimer) {
                clearTimeout(autoHideTimer);
                autoHideTimer = null;
            }

            if (container.classList.contains('active')) {
                // 隐藏工具栏
                container.classList.remove('active');
            } else {
                // 显示工具栏
                container.classList.add('active');

                // 只在电脑端设置自动隐藏
                if (!isMobileDevice()) {
                    // 设置5分钟后自动隐藏
                    autoHideTimer = setTimeout(() => {
                        container.classList.remove('active');
                        autoHideTimer = null;
                    }, 600000); // 5分钟 = 300000毫秒
                }
            }
        };





        // 鼠标悬停效果（仅PC端）
        if (!isMobile) {
            btn.addEventListener('mouseenter', () => {
                btn.style.opacity = '1';
            });
            btn.addEventListener('mouseleave', () => {
                btn.style.opacity = '0.3';
            });
        }

        document.body.appendChild(btn);
    }


    // 加载行政区划数据（只加载一次）
    async function loadAreaData() {
        if (areaDataCache || areaDataLoadAttempted) return areaDataCache;
        areaDataLoadAttempted = true;

        return new Promise((resolve) => {
            GM_xmlhttpRequest({
                method: "GET",
                url: "https://gitee.com/modood/Administrative-divisions-of-China/raw/master/dist/areas.json",
                onload: function(response) {
                    try {
                        areaDataCache = JSON.parse(response.responseText);
                        resolve(areaDataCache);
                    } catch (e) {
                        console.error("解析 JSON 失败:", e);
                        resolve([]);
                    }
                },
                onerror: function(error) {
                    console.error("请求失败:", error);
                    resolve([]);
                }
            });
        });
    }



    /**
     * 获取订单编号
     * @returns {Array} 订单编号数组
     */
    function getOrderNumbers() {
        try {
            // 获取所有表格行
            const rows = document.querySelectorAll('.el-table__body .el-table__row');
            if (!rows || rows.length === 0) return [];

            const orderNumbers = [];
            let hasChecked = false;

            // 首先检查是否有选中的行
            for (const row of rows) {
                const checkbox = row.querySelector('.el-checkbox__input input[type="checkbox"]');
                if (checkbox && checkbox.checked) {
                    hasChecked = true;
                    break;
                }
            }

            // 遍历所有行获取订单号
            for (const row of rows) {
                // 检查是否只获取选中的行
                if (hasChecked) {
                    const checkbox = row.querySelector('.el-checkbox__input input[type="checkbox"]');
                    if (!checkbox || !checkbox.checked) continue;
                }

                // 尝试多种方式获取订单号
                let orderNumberElement = row.querySelector('.ylt-link'); // 订单审核页面
                if (!orderNumberElement || !/^\d{11}$/.test(orderNumberElement.textContent.trim())) {
                    orderNumberElement = row.querySelector('td:nth-child(2) .cell'); // 订单查询页面
                }
                if (!orderNumberElement || !/^\d{11}$/.test(orderNumberElement.textContent.trim())) {
                    orderNumberElement = row.querySelector('td.el-table_1_column_2 .cell'); // 分拨处理页面
                }
                if (!orderNumberElement || !/^\d{11}$/.test(orderNumberElement.textContent.trim())) {
                    orderNumberElement = row.querySelector('td.el-table_2_column_21 .cell'); // 其他页面
                }
                if (!orderNumberElement || !/^\d{11}$/.test(orderNumberElement.textContent.trim())) {
                    continue;
                }

                const orderNumber = orderNumberElement.textContent.trim();
                if (/^\d{11}$/.test(orderNumber)) {
                    orderNumbers.push(orderNumber);
                }
            }

            return orderNumbers;
        } catch (e) {
            console.error('获取订单编号失败:', e);
            return [];
        }
    }

    // 创建条码/二维码显示界面
    //所有包含style.margin的地方（控制上下间距）
    //所有包含style.gap的地方（控制横向间距）
    //按钮的style.padding（控制按钮大小）
    function createBarcodeUI() {
        if (barcodeDisplay) {
            updateBarcodeDisplay();
            return barcodeDisplay;
        }

        barcodeDisplay = document.createElement('div');
        barcodeDisplay.id = 'barcode-display';

        // 关闭按钮（右上角）
        const closeBtn = document.createElement('button');
        closeBtn.id = 'barcode-close';
        closeBtn.innerHTML = '×';
        closeBtn.style.position = 'absolute';
        closeBtn.style.top = '10px';
        closeBtn.style.right = '10px';
        closeBtn.onclick = () => {
            document.body.removeChild(barcodeDisplay);
            barcodeDisplay = null;
        };

        // 标题（可根据需要调整下方margin）
        const title = document.createElement('h3');
        title.textContent = '订单条码/二维码';
        title.style.margin = '5px 0 10px 0'; // 上 右 下 左
        title.style.textAlign = 'center';

        // 选项区域（横向排列，增加间距）
        const optionsDiv = document.createElement('div');
        optionsDiv.id = 'barcode-options';
        optionsDiv.style.display = 'flex';
        optionsDiv.style.justifyContent = 'center';
        optionsDiv.style.gap = '20px'; // 选项间横向间距
        optionsDiv.style.margin = '0 0 0 0'; // 上 右 下 左

        // 单选按钮（可根据需要调整label样式）
        const createOption = (value, text) => {
            const container = document.createElement('label');
            container.style.display = 'flex';
            container.style.alignItems = 'center';
            container.style.gap = '5px';

            const input = document.createElement('input');
            input.type = 'radio';
            input.name = 'barcode-display-mode';
            input.value = value;
            input.checked = displayMode === value;
            input.onchange = () => {
                displayMode = value;
                updateBarcodeDisplay();
            };

            const span = document.createElement('span');
            span.textContent = text;

            container.append(input, span);
            return container;
        };

        optionsDiv.append(
            createOption('barcode', '条码'),
            createOption('qrcode', '二维码'),
            createOption('both', '两者都显示')
        );

        // 条码容器（可根据需要调整margin）
        const barcodeContainer = document.createElement('div');
        barcodeContainer.id = 'barcode-container';
        barcodeContainer.style.margin = '0 0'; // 上下 左右

        // 二维码容器（可根据需要调整margin）
        const qrcodeContainer = document.createElement('div');
        qrcodeContainer.id = 'qrcode-container';
        qrcodeContainer.style.margin = '0 0'; // 上下 左右

        // 导航区域（横向排列，增加间距）
        const navDiv = document.createElement('div');
        navDiv.id = 'barcode-nav';
        navDiv.style.display = 'flex';
        navDiv.style.justifyContent = 'center';
        navDiv.style.alignItems = 'center';
        navDiv.style.gap = '15px'; // 按钮间横向间距
        navDiv.style.margin = '15px 0 15px 0'; // 上 右 下 左

        // 上一条按钮
        const prevBtn = document.createElement('button');
        prevBtn.textContent = '上一条';
        prevBtn.style.padding = '6px 12px'; // 可根据需要调整
        prevBtn.onclick = () => {
            if (currentBarcodeIndex > 0) {
                currentBarcodeIndex--;
                updateBarcodeDisplay();
            }
        };

        // 计数器（可根据需要调整宽度）
        const counter = document.createElement('span');
        counter.id = 'barcode-counter';
        counter.style.minWidth = '80px';
        counter.style.textAlign = 'center';

        // 下一条按钮
        const nextBtn = document.createElement('button');
        nextBtn.textContent = '下一条';
        nextBtn.style.padding = '6px 12px'; // 与上一条保持一致
        nextBtn.onclick = () => {
            if (currentBarcodeIndex < barcodeData.length - 1) {
                currentBarcodeIndex++;
                updateBarcodeDisplay();
            }
        };

        // 保存全部按钮（绿色样式）
        const saveAllBtn = document.createElement('button');
        saveAllBtn.id = 'save-all-btn';
        saveAllBtn.textContent = '保存全部';
        saveAllBtn.style.padding = '6px 12px';
        saveAllBtn.style.backgroundColor = '#67c23a';
        saveAllBtn.style.color = 'white';
        saveAllBtn.onclick = saveAllBarcodes;

        // 组装导航区域
        navDiv.append(prevBtn, counter, nextBtn, saveAllBtn);

        // 组装所有元素
        barcodeDisplay.append(
            closeBtn,
            title,
            optionsDiv,
            barcodeContainer,
            qrcodeContainer,
            navDiv
        );

        document.body.appendChild(barcodeDisplay);
        return barcodeDisplay;
    }

    // 显示条码/二维码界面
    function showBarcodeUI(data) {
        if (data && data.length > 0) {
            barcodeData = data;
        } else {
            barcodeData = getOrderNumbers();
            if (barcodeData.length === 0) {
                alert('没有可用的订单号数据');
                return;
            }
        }

        currentBarcodeIndex = 0;
        createBarcodeUI();
        updateBarcodeDisplay();
    }

    // 更新条码显示
    function updateBarcodeDisplay() {
        if (!barcodeDisplay) return;

        const currentData = barcodeData[currentBarcodeIndex];
        const barcodeContainer = document.getElementById('barcode-container');
        const qrcodeContainer = document.getElementById('qrcode-container');

        barcodeContainer.innerHTML = '';
        qrcodeContainer.innerHTML = '';

        if (displayMode === 'barcode' || displayMode === 'both') {
            const barcodeSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
            barcodeSvg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
            barcodeSvg.id = 'barcode-svg';
            barcodeContainer.appendChild(barcodeSvg);

            try {
                JsBarcode(barcodeSvg, currentData, {
                    ...BARCODE_CONFIG,
                    xmlDocument: document
                });
            } catch (e) {
                console.error('生成条码失败:', e);
                barcodeContainer.innerHTML = '<div style="color:red;">条码生成失败，请确保订单号有效</div>';
            }
        }

        if (displayMode === 'qrcode' || displayMode === 'both') {
            QRCode.toCanvas(currentData, { width: 200 }, (error, canvas) => {
                if (error) {
                    console.error('生成二维码失败:', error);
                    qrcodeContainer.innerHTML = '<div style="color:red;">二维码生成失败</div>';
                } else {
                    qrcodeContainer.appendChild(canvas);
                    // 添加文本显示
                    const textDiv = document.createElement('div');
                    textDiv.className = 'qrcode-text';
                    textDiv.textContent = currentData;
                    qrcodeContainer.appendChild(textDiv);
                }
            });
        }

        document.getElementById('barcode-counter').textContent = `${currentBarcodeIndex + 1}/${barcodeData.length}`;
        document.querySelector('#barcode-nav button:first-child').disabled = currentBarcodeIndex === 0;
        document.querySelector('#barcode-nav button:nth-child(3)').disabled = currentBarcodeIndex === barcodeData.length - 1;
    }

    // 保存所有条码/二维码
    function saveAllBarcodes() {
        if (!barcodeData || barcodeData.length === 0) {
            alert('没有可保存的数据');
            return;
        }

        const saveBarcode = displayMode === 'barcode' || displayMode === 'both';
        const saveQrcode = displayMode === 'qrcode' || displayMode === 'both';

        barcodeData.forEach((data) => {
            const filenameBase = data.replace(/[^a-zA-Z0-9]/g, '_');

            // 保存条码
            if (saveBarcode) {
                try {
                    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
                    JsBarcode(svg, data, {
                        ...BARCODE_CONFIG,
                        xmlDocument: document
                    });
                    const svgData = new XMLSerializer().serializeToString(svg);

                    const canvas = document.createElement('canvas');
                    canvas.width = 500;
                    canvas.height = 150;
                    const ctx = canvas.getContext('2d');

                    const img = new Image();
                    img.onload = function() {
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                        canvas.toBlob((blob) => {
                            const url = URL.createObjectURL(blob);
                            const filename = displayMode === 'both'
                            ? `条码_${filenameBase}.png`
                            : `${filenameBase}.png`;
                            GM_download(url, filename);
                        }, 'image/png');
                    };
                    img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
                } catch (e) {
                    console.error(`保存条码失败 (${data}):`, e);
                }
            }

            // 保存二维码
            if (saveQrcode) {
                try {
                    QRCode.toDataURL(data, { width: 200 }, (error, url) => {
                        if (!error) {
                            const filename = displayMode === 'both'
                            ? `二维码_${filenameBase}.png`
                            : `${filenameBase}.png`;
                            GM_download(url, filename);
                        } else {
                            console.error(`生成二维码失败 (${data}):`, error);
                        }
                    });
                } catch (e) {
                    console.error(`保存二维码失败 (${data}):`, e);
                }
            }
        });

        alert(`已开始保存 ${barcodeData.length} 个条码/二维码，请查看浏览器下载列表`);
    }


    // showCustomAlert函数，优化单行显示，添加位置参数，宽度80%
    function showCustomAlert(content, position = {}, widthPercentage = 60, heightPercentage = 50) {
        // 移除旧弹窗
        const oldAlert = document.getElementById('ylt-custom-alert');
        if (oldAlert) oldAlert.remove();

        // 创建弹窗容器
        const alertBox = document.createElement('div');
        alertBox.id = 'ylt-custom-alert';

        // 设置宽度为自定义百分比（默认为80%）
        alertBox.style.width = `${widthPercentage}%`;
        alertBox.style.maxWidth = '90%'; // 防止过大
        alertBox.style.minWidth = '300px'; // 最小宽度

        // 设置高度（如果指定）
        if (heightPercentage !== null) {
            alertBox.style.height = `${heightPercentage}%`;
            alertBox.style.maxHeight = '90%'; // 防止过大
            alertBox.style.minHeight = '200px'; // 最小高度
            alertBox.style.overflowY = 'auto'; // 添加垂直滚动条
        }

        // 设置位置
        if (position.left && position.top) {
            alertBox.style.left = position.left;
            alertBox.style.top = position.top;
            alertBox.style.transform = 'none';
        } else {
            alertBox.style.left = '50%';
            alertBox.style.top = '50%';
            alertBox.style.transform = 'translate(-50%, -50%)';
        }

        // 创建固定标题栏
        const header = document.createElement('div');
        header.className = 'ylt-alert-header';
        header.innerHTML = `
        <span class="ylt-alert-title">药链通统计结果</span>
        <button class="ylt-alert-close">×</button>
    `;

        // 创建可拖动功能
        header.onmousedown = function(e) {
            const startX = e.clientX;
            const startY = e.clientY;
            const rect = alertBox.getBoundingClientRect();
            const startLeft = rect.left;
            const startTop = rect.top;

            function moveAt(e) {
                alertBox.style.left = startLeft + e.clientX - startX + 'px';
                alertBox.style.top = startTop + e.clientY - startY + 'px';
                alertBox.style.transform = 'none';
            }

            document.onmousemove = moveAt;

            document.onmouseup = function() {
                document.onmousemove = null;
                document.onmouseup = null;
            };
        };

        // 创建可滚动内容区
        const contentBox = document.createElement('div');
        contentBox.className = 'ylt-alert-content';

        // 优化单行显示 - 不换行，添加水平滚动条
        contentBox.style.whiteSpace = 'nowrap';
        contentBox.style.overflowX = 'auto';
        contentBox.style.padding = '15px';

        // 如果指定了高度，内容区也应有自适应高度
        if (heightPercentage !== null) {
            contentBox.style.height = 'calc(100% - 40px)'; // 减去标题栏高度
            contentBox.style.overflowY = 'auto';
        }

        // 替换换行符为<br>，但保持单行内容不换行
        contentBox.innerHTML = content.replace(/\n/g, '<br>');

        // 组装元素
        alertBox.appendChild(header);
        alertBox.appendChild(contentBox);
        document.body.appendChild(alertBox);

        // 关闭功能
        header.querySelector('.ylt-alert-close').onclick = () => {
            document.body.removeChild(alertBox);
        };
    }



    // 创建单选按钮
    function createRadioOption(value, label, checked, onChange) {
        const container = document.createElement('label');
        const input = document.createElement('input');
        input.type = 'radio';
        input.name = 'barcode-display-mode';
        input.value = value;
        input.checked = checked;
        input.onchange = onChange;
        const span = document.createElement('span');
        span.textContent = label;
        container.append(input, span);
        return container;
    }

    // 新增的处理剪辑版二维码的函数
    async function handleClipboardBarcode() {
        try {
            // 首先检查是否有选中的文本
            const selectedText = window.getSelection().toString().trim();
            let textToEncode = selectedText;

            if (!textToEncode) {
                // 如果没有选中的文本，尝试从剪贴板获取
                try {
                    textToEncode = await navigator.clipboard.readText();
                } catch (e) {
                    console.error('读取剪贴板失败:', e);
                    alert('无法读取剪贴板内容，请确保已授予剪贴板访问权限\n或手动选择文本后重试');
                    return;
                }
            }

            if (!textToEncode) {
                alert('没有找到可用的文本，请先选择文本或复制内容到剪贴板');
                return;
            }

            // 处理文本内容 - 按换行符分割成数组
            const data = textToEncode.split('\n')
            .map(line => line.trim())
            .filter(line => line.length > 0);

            if (data.length === 0) {
                alert('没有找到有效的文本内容');
                return;
            }

            // 调用显示函数
            showBarcodeUI(data);
        } catch (e) {
            console.error('处理选中&剪辑版二维码失败:', e);
            alert('处理选中&剪辑版二维码时出错: ' + e.message);
        }
    }

    // 复制订单号
    function CopyDingdanBianHao(showAlert = true) {
        try {
            const orderNumbers = getOrderNumbers();
            if (orderNumbers.length === 0) {
                if (showAlert) alert('未找到可复制的订单号');
                return false;
            }

            const clipboardText = orderNumbers.join('\n');
            GM_setClipboard(clipboardText, "text");

            if (showAlert) {
                const message = `已复制${orderNumbers.length}个订单号：\n${clipboardText}`;
                alert(message);
            }
            return true;
        } catch (e) {
            if (showAlert) alert('复制订单号失败：' + e.message);
            return false;
        }
    }

    // 打印功能
    function doPrint() {
        window.print();
    }

    // 快速搜索
    function FastSearchonclick(searchText) {
        try {
            const inputEvent = new Event('input', {
                bubbles: true,
                cancelable: true
            });
            let companyInput
            //companyInput = document.querySelector('label[for="companyName"] + .el-form-item__content .el-input__inner');//搜索所属企业
            if (!companyInput) {
                companyInput = document.querySelector('label[for="sendCompanyName"] + .el-form-item__content .el-input__inner');//搜索发货企业
            }

            if (companyInput) {
                companyInput.value = searchText;
                companyInput.dispatchEvent(inputEvent);

                const buttons = document.querySelectorAll('button.el-button.el-button--primary');
                const searchButton = Array.from(buttons).find(button =>
                                                              button.querySelector('span')?.textContent.trim() === '搜索'
                                                             );

                if (searchButton) {
                    searchButton.click();
                } else {
                    alert("未找到搜索按钮");
                }
            } else {
                alert("未找到公司名称输入框");
            }
        } catch (e) {
            alert('快速搜索失败：' + e.message);
        }
    }

    // API请求 AuthToken(845138ac42174208870428210a4967e8)
    async function makeApiRequest(apiName, params) {
        try {
            const config = API_CONFIG[apiName];
            if (!config) {
                throw new Error(`未找到API配置: ${apiName}`);
            }

            /* 原方法：获取authToken方法，多个authToken排序使用第一个
            let authToken = null;
            const authTokenKeys = Object.keys(localStorage).filter(key => key.startsWith('AuthToken'));
            if (authTokenKeys.length > 0) {
                authTokenKeys.sort((a, b) => localStorage[b].length - localStorage[a].length);
                authToken = localStorage[authTokenKeys[0]].replace(/^"+|"+$/g, '').trim();
            }
            */

            let authToken = null;
            const authTokenKeys = Object.keys(localStorage).filter(key => key.startsWith('AuthToken'));

            if (authTokenKeys.length > 0) {
                // 优先选择包含845138的token
                const specialToken = authTokenKeys.find(k => k.includes('845138'));
                authTokenKeys.sort((a, b) => {
                    if (specialToken) return a === specialToken ? -1 : 1;
                    return localStorage[b].length - localStorage[a].length;
                });
                authToken = localStorage[authTokenKeys[0]].replace(/^"+|"+$/g, '').trim();
            }

            if (!authToken) {
                throw new Error('无法获取授权令牌，请确保已登录');
            }

            let body = config.bodyTemplate;
            for (const key in params) {
                body = body.replace(new RegExp(`\\$\\{${key}\\}`, 'g'), encodeURIComponent(params[key]));
            }

            const response = await fetch(config.url, {
                method: config.method,
                headers: {
                    'Authorization': authToken,
                    'Content-Type': config.contentType,
                },
                body: body,
                credentials: 'include'
            });

            if (!response.ok) {
                throw new Error(`HTTP错误: ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error(`API请求失败: ${error.message}`);
            throw error;
        }
    }

    // 修改配送路线（优化版）
    async function changeShippingRoute(apiName) {
        try {
            const orderNumbers = getOrderNumbers();
            if (orderNumbers.length === 0) {
                alert('未找到有效的订单号');
                return;
            }

            const results = [];
            let resultMessage = "订单处理结果：\n\n";

            for (const orderCode of orderNumbers) {
                try {
                    const data = await makeApiRequest(apiName, { orderCode });
                    results.push({ success: true, orderCode, data });

                    // 提取message信息
                    const message = data.message || (data.data && data.data.message) || "操作成功";
                    resultMessage += `${orderCode} ${message}\n`;

                    console.log(`订单 ${orderCode} 处理结果:`, data);
                } catch (error) {
                    results.push({ success: false, orderCode, error: error.message });
                    resultMessage += `${orderCode} 处理失败: ${error.message}\n`;
                    console.error(`订单 ${orderCode} 处理失败:`, error);
                }
            }

            // 显示汇总结果
            alert(resultMessage);

            const successCount = results.filter(r => r.success).length;
            const failCount = results.filter(r => !r.success).length;
            console.log(`处理完成: ${successCount}成功, ${failCount}失败`);

        } catch (e) {
            alert(`操作发生错误: ${e.message}`);
        }
    }

    // 获取统计订单明细
    async function getOrderDetailsSummary(displayMode = 3) {
        try {
            const orderNumbers = getOrderNumbers();
            if (orderNumbers.length === 0) {
                alert('未找到有效的订单号');
                return;
            }

            // 创建进度提示元素
            const progress = document.createElement('div');
            progress.style.cssText = `
            position: fixed;
            top: 60px;
            left: 50%;
            transform: translateX(-50%);
            background: #409eff;
            color: white;
            padding: 8px 15px;
            border-radius: 4px;
            z-index: 99999;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        `;
            document.body.appendChild(progress);

            const totalOrders = orderNumbers.length;
            let summary1 = [];
            let summary2 = {};
            let errorOrders = [];

            for (let i = 0; i < orderNumbers.length; i++) {
                const orderCode = orderNumbers[i];
                try {
                    // 更新进度提示
                    progress.textContent = `正在获取【${i+1}/${totalOrders}】 订单号：${orderCode}`;

                    const response = await makeApiRequest('orderInfo', { orderCode });

                    if (!response?.data?.main || !response.data.items) {
                        throw new Error('接口返回数据结构异常');
                    }

                    const orderNumber = response.data?.expand?.ordercode || orderCode;
                    const companyName = response.data.main.receiveCompanyName || '未知单位';
                    const cityName = response.data.main.receiveCityAreaName || '未知城市';

                    const orderInfo = {
                        code: orderNumber,
                        company: companyName,
                        city: cityName,
                        items: []
                    };

                    response.data.items.forEach(item => {
                        if (!item.durgName || item.num === undefined) {
                            errorOrders.push(`${orderNumber}：药品数据不完整`);
                            return;
                        }

                        const [itemName] = item.durgName.split('-');
                        const specification = item.trpInnerPacking || '无规格';
                        const batchNumber = item.facBatchNumber || '无批号';
                        const quantity = parseInt(item.num) || 0;

                        orderInfo.items.push(`${itemName}-${specification}-${batchNumber}-${quantity}`);

                        const summaryKey = `${itemName}-${specification}-${batchNumber}`;
                        summary2[summaryKey] = (summary2[summaryKey] || 0) + quantity;
                    });

                    summary1.push(orderInfo);
                } catch (e) {
                    errorOrders.push(`${orderCode}：${e.message}`);
                    console.error(`订单 ${orderCode} 处理失败:`, e);
                }

                // 添加短暂延迟避免UI卡顿
                await new Promise(resolve => setTimeout(resolve, 50));
            }

            // 移除进度提示
            progress.remove();

            // 构建结果文本
            let result = '';

            if ([1, 3].includes(displayMode)) {
                result += `▓▓▓ 按订单统计 (共${totalOrders}个订单) ▓▓▓\n`;
                summary1.forEach(order => {
                    result += `📦 订单号：${order.code}\n🏢 收货单位：${order.company}（${order.city}）\n`;
                    order.items.forEach(item => result += `    ├─ ${item}\n`);
                    result += '\n';
                });
            }

            if ([2, 3].includes(displayMode)) {
                result += `▓▓▓ 按品名+规格+批号汇总 (当前${totalOrders}个订单) ▓▓▓\n`;
                Object.entries(summary2).forEach(([key, count]) => {
                    const [name, spec, batch] = key.split('-');
                    result += `    ▸ ${name}-${spec}-${batch}-${count}件\n`;
                });
                result += '\n';
            }

            if (errorOrders.length > 0) {
                result += `⚠ 失败订单 (${errorOrders.length})：\n${errorOrders.join('\n')}`;
            }

            showCustomAlert(result);

        } catch (e) {
            alert('统计失败：' + e.message);
            console.error('全局错误:', e);
        }
    }



    // 搜索通讯录收货人
    async function SearchReceiver() {
        try {
            // 静默加载数据（失败不影响主流程）
            if (!areaDataCache && !areaDataLoadAttempted) {
                await loadAreaData();
            }

            // 搜索类型选择对话框
            const searchType = await new Promise(resolve => {
                const dialog = document.createElement('div');
                dialog.innerHTML = `
                <div style="position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);
                    background:#fff;padding:20px;border-radius:8px;box-shadow:0 0 20px rgba(0,0,0,0.3);
                    z-index:99999;min-width:300px;">
                    <h3 style="margin-top:0;text-align:center;">选择搜索类型</h3>
                    <div style="margin-bottom:15px;">
                        ${['companyName', 'name', 'mobile', 'phone', 'address'].map(type => `
                            <label style="display:block;margin:8px 0;">
                                <input type="radio" name="searchType" value="${type}"
                                    ${type === 'mobile' ? 'checked' : ''}><!-- 修改默认选中 -->
                                ${getSearchTypeName(type)}
                            </label>
                        `).join('')}
                    </div>
                    <div style="display:flex;justify-content:space-between;">
                        <button id="cancelBtn" style="padding:5px 15px;background:#f56c6c;">取消</button>
                        <button id="confirmBtn" style="padding:5px 15px;background:#409eff;">确定</button>
                    </div>
                </div>
            `;

                document.body.appendChild(dialog);

                dialog.querySelector('#confirmBtn').onclick = () => {
                    const selected = dialog.querySelector('input[name="searchType"]:checked').value;
                    document.body.removeChild(dialog);
                    resolve(selected);
                };

                dialog.querySelector('#cancelBtn').onclick = () => {
                    document.body.removeChild(dialog);
                    resolve(null);
                };
            });

            if (!searchType) return;

            // 获取搜索关键词
            const keyword = prompt(`请输入${getSearchTypeName(searchType)}关键字:`);
            if (!keyword) return;

            // 构建请求参数
            const params = {
                companyName: '',
                name: '',
                mobile: '',
                phone: '',
                address: ''
            };
            // 只设置选中的搜索类型参数
            params[searchType] = keyword;

            // API请求
            const response = await makeApiRequest('SearchInfo', params);

            if (!response?.data?.records?.length) {
                alert('未找到匹配的通讯录信息');
                return;
            }

            // id转行政区
            const results = response.data.records.map(record => {
                let areaName = '无行政区';
                if (record.areaid && areaDataCache?.length) {
                    const found = areaDataCache.find(item => item.code === record.areaid);
                    areaName = found?.name || '无行政区';
                }

                return [
                    record.companyName || '无',
                    record.name || '无',
                    `手机:${record.mobile || '无'}`,
                    `座机:${record.phone || '无'}`,
                    areaName,
                    record.address || '无'
                ].join(' | ');
            });

            areaDataCache = null; // 释放内存

            // 显示结果
            if (results.length > 0) {
                showCustomAlert(`找到 ${results.length} 条信息:\n\n${results.join('\n\n')}`);
            } else {
                alert('未找到匹配的通讯录信息');
            }
        } catch (e) {
            console.error('搜索流程异常:', e);
            alert('操作失败: ' + (e.message || '未知错误'));
        }
    }

    // 辅助函数：获取搜索通讯录类型的中文名称
    function getSearchTypeName(type) {
        const names = {
            companyName: '收货企业',
            name: '收货人',
            mobile: '手机',
            phone: '座机',
            address: '目的地'
        };
        return names[type] || type;
    }




    // 创建下拉菜单（优化版）
    function createDropdownButton(title, items) {
        const isMobile = isMobileDevice();
        const dropdown = document.createElement('div');
        dropdown.className = 'ylt-helper-dropdown';

        const button = document.createElement('button');
        button.textContent = title;
        button.style.padding = isMobile ? '8px 12px' : '5px 10px';
        button.style.fontSize = isMobile ? '16px' : '14px';

        const dropdownContent = document.createElement('div');
        dropdownContent.className = 'ylt-helper-dropdown-content';
        dropdownContent.style.minWidth = isMobile ? '160px' : '120px';

        // 内部函数：关闭所有下拉菜单
        const closeAllDropdowns = () => {
            document.querySelectorAll('.ylt-helper-dropdown-content').forEach(content => {
                content.style.display = 'none';
                content.dataset.isOpen = 'false';
            });
        };

        // 内部函数：切换当前下拉菜单
        const toggleCurrentDropdown = () => {
            const isOpen = dropdownContent.dataset.isOpen === 'true';

            if (!isOpen) {
                closeAllDropdowns();
                dropdownContent.style.display = 'block';
                dropdownContent.dataset.isOpen = 'true';
            } else {
                dropdownContent.style.display = 'none';
                dropdownContent.dataset.isOpen = 'false';
            }
        };

        // 初始化状态
        dropdownContent.dataset.isOpen = 'false';

        // 添加菜单项
        items.forEach(item => {
            const itemButton = document.createElement('button');
            itemButton.textContent = item.text;
            itemButton.style.padding = isMobile ? '12px 16px' : '8px 16px';
            itemButton.style.fontSize = isMobile ? '16px' : '14px';
            itemButton.onclick = (e) => {
                e.stopPropagation();
                item.action();
                dropdownContent.style.display = 'none';
                dropdownContent.dataset.isOpen = 'false';
            };
            dropdownContent.appendChild(itemButton);
        });

        // PC端 - 鼠标悬停效果
        if (!isMobile) {
            dropdown.addEventListener('mouseenter', () => {
                closeAllDropdowns();
                dropdownContent.style.display = 'block';
                dropdownContent.dataset.isOpen = 'true';
            });

            dropdown.addEventListener('mouseleave', () => {
                dropdownContent.style.display = 'none';
                dropdownContent.dataset.isOpen = 'false';
            });
        }

        // 移动端 - 点击效果
        if (isMobile) {
            button.onclick = (e) => {
                e.stopPropagation();
                toggleCurrentDropdown();
            };
        }

        // 点击页面其他位置关闭菜单
        document.addEventListener('click', (e) => {
            if (!dropdown.contains(e.target)) {
                closeAllDropdowns();
            }
        });

        dropdown.appendChild(button);
        dropdown.appendChild(dropdownContent);

        return dropdown;
    }




    // 创建顶部工具栏容器  工具栏容器初始化部分
    const helperContainer = document.createElement('div');
    helperContainer.id = 'ylt-helper-container';
    // 移动端默认显示工具栏
    if (isMobileDevice()) {
        helperContainer.classList.add('active');
    }
    document.body.prepend(helperContainer);



    // 添加下拉菜单到工具栏
    const moreFunctionsDingdan = createDropdownButton('快捷导航', [
        { text: '订单查询', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/orders/search';}},
        { text: '在线下单', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/corder/general';}},
        { text: '【审核】', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/orders/audit';}},
        { text: '【分拨】', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/distrib/distrib';}},
        { text: '派车记录', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/dispatch/record';}},
        { text: '库存查询', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/storage/stock';}},
        { text: '手动入库', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/storage/handle/manual?mode=in';}},
        { text: '手动出库', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/storage/handle/manual?mode=out';}},
        { text: '云仓处理', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/storage/handle';}},
        { text: '云仓记录', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/storage/record';}},
        { text: '【盘点】', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/storage/stock/check';}},
        { text: '通讯录', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/cresource/contacts';}},
        { text: '货品管理', action: () => {window.location.href = 'https://ylt.cdhywl.cn/pt/#/cresource/drug';}},

    ]);

    const moreFunctionsMenu = createDropdownButton('更多功能', [
        { text: '通过审核', action: () => changeShippingRoute('verify') },
        { text: '重新匹配', action: () => changeShippingRoute('rematchLine') },
        { text: '改【城配】', action: () => changeShippingRoute('rematchDistribution') },
        { text: '改【中通】', action: () => changeShippingRoute('detailChangeOrderLineMatchZT') },
        { text: '改【安能】', action: () => changeShippingRoute('detailChangeOrderLineMatchAN') },
        { text: '打印订单',action: () => {const printBtn = Array.from(document.querySelectorAll('button span')) .find(el => el.textContent === '打印订单');if (printBtn) printBtn.parentElement.click();}},
        { text: '打印标签',action: () => {const printBtn = Array.from(document.querySelectorAll('button span')) .find(el => el.textContent === '打印标签');if (printBtn) printBtn.parentElement.click();}},
        { text: '打印Print', action: doPrint },
        { text: '搜索【通讯录】', action: SearchReceiver },
        { text: '统计订单明细', action: getOrderDetailsSummary },
        { text: '复制订单号', action: () => CopyDingdanBianHao() },
        { text: '生成条码/二维码', action: () => showBarcodeUI() },
        { text: '选中/剪辑版条码', action: handleClipboardBarcode },
    ]);

    const companyMenu = createDropdownButton('快搜企业', [
        { text: '彩虹', action: () => FastSearchonclick("彩虹") },
        { text: '启航', action: () => FastSearchonclick("启航") },
        { text: '徽乐', action: () => FastSearchonclick("徽乐") },
        { text: '和济方', action: () => FastSearchonclick("和济方") },
        { text: '阿斯迈', action: () => FastSearchonclick("阿斯迈") },
        { text: '春天听花', action: () => FastSearchonclick("春天") },
        { text: '高原', action: () => FastSearchonclick("高原明珠") },

    ]);

    helperContainer.appendChild(moreFunctionsDingdan);
    helperContainer.appendChild(moreFunctionsMenu);
    helperContainer.appendChild(companyMenu);

    // 创建激活按钮
    createActivationButton();

    console.log('药链通增强版已加载');
})();